package myJs.user.centrifuge

import myJs.Implicits._
import myJs.Utils.layer
import myJs.myPkg._
import myJs.myPkg.jquery._
import myJs.tool.Pojo.FilterContentData
import myJs.tool.Tool
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all._

import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("ReRunMission")
object ReRunMission {

  var missionId = ""

  @JSExport("init")
  def init = {
    NewMission.refreshDb
    fillMission.foreach { x =>
      selectMission
      NewMission.getCpuNum { cpuNum =>
        bootStrapValidator(cpuNum)
        $("#form").bv.revalidateField("missionName")
      }
    }
    registerEvent
  }

  def selectMission = {
    missionId = $(":input[name='hideMissionId']").`val`().toString
    $(":input[name='missionId']").select2Val(missionId)
    if (missionId != "") {
      $(":input[name='missionId']").select2Val(missionId).trigger("change")
    }
  }

  def fillMission = {
    val url = g.jsRoutes.controllers.CentrifugeController.getAllReRunMissionNames().url.toString
    Ajax.get(url = s"${url}").map { xhr =>
      val rs = xhr.responseText.toJArJAn
      val options = Select2Options.placeholder("选择一个任务").data(rs)
      $(":input[name='missionId']").select2(options)
    }
  }

  def registerEvent = {
    $(document.body).on("change", s".myMissionName", "", (y: Element) => {
      missionNameChange(y)
    })
    $(document.body).on("click", s".myRun", "", (y: Element) => {
      myRun
    })
  }

  def missionNameChange(y: Element) = {
    val missionId = $(y).find(">option:selected").`val`().toString
    refreshMissionName(missionId)
    refreshConfig(missionId)
  }

  def refreshConfig(missionId: String) = {
    val url = g.jsRoutes.controllers.CentrifugeController.getConfig().url.toString
    Ajax.get(url = s"${url}?missionId=${missionId}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      Tool.fillByNames(rs.toMyJDS)
    }
  }

  def refreshMissionName(missionId: String) = {
    val url = g.jsRoutes.controllers.CentrifugeController.getMissionById().url.toString
    Ajax.get(url = s"${url}?missionId=${missionId}").map { xhr =>
      val dict = JSON.parse(xhr.responseText).toJDS
      Tool.getInputByName("missionName").`val`(s"${dict("missionName")}_reRun")
      g.$("#form").bootstrapValidator("revalidateField", "missionName")
    }
  }

  def myRun = {
    val formJq = $("#form")
    val bv = formJq.bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val element = div(id := "content",
        span(id := "info", "正在运行",
          span(id := "progress")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.icon(16).shade(0.01).time(20000000)
      val index = layer.msg(element, layerOptions)
      val formData = formJq.serialize()
      val url = g.jsRoutes.controllers.CentrifugeController.reRunMission().url.toString
      Ajax.post(url = s"${url}", data = formData, headers = Map("Content-Type" -> "application/x-www-form-urlencoded"),
        responseType = "application/json").map { xhr =>
        val rs = xhr.responseText.toJDJAn
        layer.close(index)
        val valid = rs("valid").toB
        if (valid) {
          window.location.href = g.jsRoutes.controllers.CentrifugeController.missionManageBefore().url.toString
        } else {
          g.swal("Error", rs.myGet("message"), "error")
        }
      }

    }
  }

  def getMissionId = {
    g.missionId.toString
  }

  def bootStrapValidator(cpuNum: Int) = {
    val url = g.jsRoutes.controllers.CentrifugeController.missionNameCheck().url.toString
    val maxNumber = Double.MaxValue
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "missionName" -> {
          val info = "任务名"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空!"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${info}已存在!",
                "url" -> url,
                "type" -> "POST",
                "delay" -> 1000
              ),
            )
          )
        },
        "trim5" -> {
          val info = "trim5"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "integer" -> js.Dictionary(
                "message" -> s"${info}必须为自然数！",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> maxNumber,
                "message" -> s"${info}必须大于等于0",
              ),
            )
          )
        },
        "trim3" -> {
          val info = "trim3"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "integer" -> js.Dictionary(
                "message" -> s"${info}必须为自然数！",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> maxNumber,
                "message" -> s"${info}必须大于等于0",
              ),
            )
          )
        },
        "threadNum" -> {
          val info = "线程数"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "integer" -> js.Dictionary(
                "message" -> s"${info}必须为整数！",
              ),
              "between" -> js.Dictionary(
                "min" -> 1,
                "max" -> maxNumber,
                "message" -> s"${info}必须大于0且小于等于${cpuNum}(服务器可用最大cpu)！",
              ),
            )
          )
        },
      )
    )
    g.$("#form").bootstrapValidator(dict)

  }


}
